package com.gopay.scheduler.job;

import com.gopay.common.constants.autosettle.SettlementExchangeConstants;
import com.gopay.common.constants.order.SettlementConstans;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.DrawOpType;
import com.gopay.common.constants.trans.PayBankOpType;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.constants.wallet.optype.Wallet01605OpType;
import com.gopay.common.constants.wallet.optype.Wallet01606OpType;
import com.gopay.common.constants.wallet.optype.Wallet01617OpType;
import com.gopay.common.cps.dao.autosettle.AsBankLimitConfigDAO;
import com.gopay.common.cps.service.autosettle.impl.AutoSettleBankCodeAdapter;
import com.gopay.common.cps.service.autosettle.impl.AutoSettleHelper;
import com.gopay.common.domain.autosettle.AsBankLimitConfig;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cps.gp.GP01301VO;
import com.gopay.common.domain.cps.transfer.Tran00700VO;
import com.gopay.common.domain.cps.transfer.Tran00701PortalVO;
import com.gopay.common.domain.cps.transfer.Tran00701VO;
import com.gopay.common.domain.cps.transfer.Tran00800VO;
import com.gopay.common.domain.cps.vo.CPSResponse;
import com.gopay.common.domain.cps.wallet.Wallet01605VO;
import com.gopay.common.domain.cps.wallet.Wallet01606VO;
import com.gopay.common.domain.cps.wallet.Wallet01617VO;
import com.gopay.common.user.dao.CloudCustAcctRelDao;
import com.gopay.common.util.DateUtils;
import com.gopay.cron.web.vo.PayOrderVo;
import com.gopay.remote.cps.autosettle.AutoSettleBankService;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.common.CallCPSHelper;
import com.gopay.scheduler.service.autosettle.AutoSettleService;
import com.gopay.sms.client.GopaySMSHttpClient;
import com.gopay.sms.common.constants.SMSAppId;
import com.gopay.sms.common.domain.RequestVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 自动结算Job
 * 
 * @AutoSettleJob.java
 * @author fanghw
 * @2014-11-5 下午3:39:35 www.gopay.com.cn Inc.All rights reserved.
 */
public class AutoSettleJob extends GopayBaseJob {
    // 日志
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 统计天数
     */
    private static final int STATI_DAYS = 15;

    private static final int RETRY = 5;

	private static final BigDecimal RESERVE_AMT_MILLION = new BigDecimal(1000000);

    /**
     * 最近一个月的法定工作日列表
     */
    private List<String> legalWorkList;

    private String startDay;

    private String today;

    @Resource(name = "callCPSHelper")
    private CallCPSHelper callCPSHelper;

    @Resource(name = "autoSettleService")
    private AutoSettleService autoSettleService;

    @Resource(name = "autoSettleHelper")
    private AutoSettleHelper autoSettleHelper;
    
    @Resource(name = "autoSettleBankCodeAdapter")
    private AutoSettleBankCodeAdapter autoSettleBankCodeAdapter;


    @Resource(name = "asBankLimitConfigDAO")
    private AsBankLimitConfigDAO asBankLimitConfigDAO;
    
	@Resource(name = "autoSettleBankRemoteService")
    private AutoSettleBankService autoSettleBankService;
	

	@Resource(name = "cloudCustAcctRelDao")
	private CloudCustAcctRelDao cloudCustAcctRelDao;


    @Override
    public void doJobInternal() {
    	
        // 当前时间
        Date curDate = new Date();
        // 初始化数据
        init(curDate);
        
        
//        doSettlementToday();
//        if (curDate.getMinutes()/5%2==0) {
        if (curDate.getHours() == 9){
        	// 执行9点D1优化任务
        	doDailySettlementJudge();
        } else if(curDate.getHours() < 10) {
            // 执行零点判断
            doZeroJudge();
        } else if (curDate.getHours() == 10) {     
            // 判断今天是否为节假日
            if (autoSettleHelper.isHoliday(curDate)) {
                // 对当天结算的并且结算日为节假日的T+N订单执行十点银企直连
                doTenBCDL();
            }
//		} else if (curDate.getHours() == 11) {
//			if (!autoSettleHelper.isHoliday(curDate)) {
//				doSettlementToday();
//			}
//		} else if (curDate.getHours() == 15) {
//			if (!autoSettleHelper.isHoliday(curDate)) {
//				doSettlementToday();
//			}
		}
        /*if (curDate.getMinutes()/5%2==0) {
        	 doZeroJudge();
        }else{
        	 if (autoSettleHelper.isHoliday(curDate)) {
                 // 对当天结算的并且结算日为节假日的T+N订单执行十点银企直连
                 doTenBCDL();
             }else{
             	doSettlementToday();
             }
        }*/
       
       

       
    }
    
    private void doDailySettlementJudge(){
    	// 查询订单之零点判断
        List<CpsGenMainOrder> manualList = autoSettleService.queryOrderByTypeForDailySettlementJudge(SettlementConstans.SETTLEMENT_OPERATION_TYPE_MANUAL);
        List<CpsGenMainOrder> autoList = autoSettleService.queryOrderByTypeForDailySettlementJudge(SettlementConstans.SETTLEMENT_OPERATION_TYPE_AUTO);

        logger.error("doDailySettlementJudge--queryOrder--manualList.size=" + manualList.size() + ", autoList.size=" + autoList.size());
        
        callCpsDailySettlementToday(autoList, SettlementConstans.SETTLEMENT_OPERATION_TYPE_AUTO);
        callCpsDailySettlementToday(manualList, SettlementConstans.SETTLEMENT_OPERATION_TYPE_MANUAL);
    }
    
    private void callCpsDailySettlementToday(List<CpsGenMainOrder> mainList, String type) {
		// 调用CPS
        CPSResponse response;
        StringBuffer sbf = new StringBuffer();
        Tran00700VO paramVo = new Tran00700VO();
        if(SettlementConstans.SETTLEMENT_OPERATION_TYPE_AUTO.equals(type)){
        	paramVo.setOpType( PayBankOpType.AUTO_SETTLE_DAILY_SETTLEMENT_LOCK_DEAL);
        }else if(SettlementConstans.SETTLEMENT_OPERATION_TYPE_MANUAL.equals(type)){
        	paramVo.setOpType( PayBankOpType.AUTO_SETTLE_DAILY_SETTLEMENT_PREPARE_TO_PAY);
        }
        for (int i = 0; i < mainList.size(); i++) {
            CpsGenMainOrder order = mainList.get(i);
            
            String gopayOrderId = order.getGopayOrderId();

            logger.error("doDailySettlementJudge------GopayOrderId=" + gopayOrderId);
            
            sbf.append(gopayOrderId).append(",");

			if ((i+1) % 20 == 0  || i == mainList.size() - 1) {
				paramVo.setGopayOrderId(sbf.toString());
				sbf = new StringBuffer();
				try {
					// 调用cps
					response = callCPSHelper.callByVOTicket(paramVo);
					if (!ProcCodeConstants.PROC_CODE_100S1000.equals(response.getRespCode())) {
						logger.error("------调用cps返回异常  response="+ response.getRespCode());
					}
				} catch (Exception e) {
					// 吃掉所有异常
					logger.error("callByVOTicket Error", e);
				}
			}
        }
	}
    
    private void doSettlementToday(){
    	Map<String,String> filterMap = new HashMap<String, String>();
    	for(int i = 0; i < RETRY; i++){
			if(!doSettlementToday(filterMap,i)){
				try {
					Thread.sleep(120000);
				} catch (InterruptedException e) {
					logger.error("线程睡眠失败",e);
				}
				continue;
			}else{
				break;
			}
		}
    }

	/**
	 * T+1优化订单
	 * @param filterMap 
	 */
	private boolean doSettlementToday(Map<String, String> filterMap,int count){
		 // 当前时间
        Date curDate = new Date();
		boolean flag = true;
        
		// 查询T+1优化订单
		List<PayOrderVo> mainList = autoSettleService.queryOrderOfSettlementToday(startDay, today);
		
		logger.error("doSettlementToday--queryOrder--mainList.size=" + mainList.size());
		
		if(CollectionUtils.isEmpty(mainList)){
			return true;
		}
		
		
		//获取银行备付金
		List<AsBankLimitConfig> asBankLimitConfigs = asBankLimitConfigDAO.findAll(AsBankLimitConfig.class);
		Map<String, Map<String, Object>> bankBalanceMap = sumMerTxnAmtByBankCode(mainList,asBankLimitConfigs);
		
		for (AsBankLimitConfig a : asBankLimitConfigs) {
			if(a.getBankAcctLastUpdTs().getHours() >= curDate.getHours()){
				if(!bankBalanceMap.containsKey(a.getBankCode())){
					logger.info("未查到包含关系 bankBalanceMap=" + bankBalanceMap + " a.getBankCode()" + a.getBankCode());
					continue;
				}
				
				BigDecimal toPayAmt = (BigDecimal)bankBalanceMap.get(a.getBankCode()).get("totalAmt");
				if(!filterMap.containsKey(a.getBankCode()) && a.getBankAcctAmt().subtract(RESERVE_AMT_MILLION).compareTo(toPayAmt) > -1){
					// 余额足以支付，则更新为锁定状态
					callCps4SettlementToday((List)bankBalanceMap.get(a.getBankCode()).get("gopayOrderIds"),true);
					
					// 发短信说哪个银行付了多少钱
					RequestVO req = new RequestVO();
					req.setAppId(SMSAppId._90000.value);
					req.setMobile(a.getMoblieNos());
					req.setContent(DateUtils.getCurrDate() + getBankName(a.getBankCode()) + "银行T+1优化付款金额为"+toPayAmt+"元，当前账户（尾号："+getAcctNo(a.getBankCode())+")余额为"+a.getBankAcctAmt()+"元");
					GopaySMSHttpClient.getInstance().createVerificationCode(req);
					logger.info(DateUtils.getCurrDate() + getBankName(a.getBankCode()) + "银行T+1优化付款金额为"+toPayAmt+"元，当前账户（尾号："+getAcctNo(a.getBankCode())+")余额为"+a.getBankAcctAmt()+"元");
					
				}else{
					callCps4SettlementToday((List)bankBalanceMap.get(a.getBankCode()).get("gopayOrderIds"),false);
					// 发短信说明备付金余额不足以支付T+1优化总额
					RequestVO req = new RequestVO();
					req.setAppId(SMSAppId._90000.value);
					req.setMobile(a.getMoblieNos());
					req.setContent(DateUtils.getCurrDate() + getBankName(a.getBankCode()) + "银行T+1优化付款金额为"+toPayAmt+"元，当前账户（尾号："+getAcctNo(a.getBankCode())+")余额为"+a.getBankAcctAmt()+"元，预计不能满足今日付款，请及时处理。");
					GopaySMSHttpClient.getInstance().createVerificationCode(req);
					logger.info(DateUtils.getCurrDate() + getBankName(a.getBankCode()) + "银行T+1优化付款金额为"+toPayAmt+"元，当前账户（尾号："+getAcctNo(a.getBankCode())+")余额为"+a.getBankAcctAmt()+"元，预计不能满足今日付款，请及时处理。");
					filterMap.put(a.getBankCode(), a.getBankCode());
				}
			}else{
				if(count==4){
					if(null != bankBalanceMap.get(a.getBankCode())){
						logger.info(a.getBankCode()+"没有T+1优化订单");
						callCps4SettlementToday((List)bankBalanceMap.get(a.getBankCode()).get("gopayOrderIds"),false);
					}
				}
				// 说明银行余额还未返回，需要重要调下查询
				logger.info(a.getBankCode()+"未查询到银行余额，需要重新查询");
				autoSettleBankService.QueryBanksCardBalanceAmt();
				flag = false;
			}
		}
		
		return flag;
		
	}

	private void callCps4SettlementToday(List<String> mainList, boolean isLockDeal) {
		// 调用CPS
        CPSResponse response;
        StringBuffer sbf = new StringBuffer();
        Tran00700VO paramVo = new Tran00700VO();
        if(isLockDeal){
        	paramVo.setOpType( PayBankOpType.AUTO_SETTLE_SETTLEMENT_TODAY_LOCK_DEAL);
        }else{
        	paramVo.setOpType( PayBankOpType.AUTO_SETTLE_SETTLEMENT_TODAY_PREPARE_4_PAY);
        }
        for (int i = 0; i < mainList.size(); i++) {
            String gopayOrderId = mainList.get(i);

            logger.error("doSettlementToday------GopayOrderId=" + gopayOrderId);
            
            sbf.append(gopayOrderId).append(",");

			if ((i+1) % 20 == 0  || i == mainList.size() - 1) {
				paramVo.setGopayOrderId(sbf.toString());
				sbf = new StringBuffer();
				try {
					// 调用cps
					response = callCPSHelper.callByVOTicket(paramVo);
					if (!ProcCodeConstants.PROC_CODE_100S1000.equals(response.getRespCode())) {
						logger.error("------调用cps返回异常  response="+ response.getRespCode());
					}
				} catch (Exception e) {
					// 吃掉所有异常
					logger.error("callByVOTicket Error", e);
				}
			}
        }
	}

	private Map<String, Map<String, Object>> sumMerTxnAmtByBankCode(List<PayOrderVo> mainList, List<AsBankLimitConfig> asBankLimitConfigs) {
		Map<String,Map<String,Object>> m = new HashMap<String, Map<String,Object>>();
		
		for (PayOrderVo p : mainList) {
//			String bankCode = getBankCode(p.getRecvBankName(),asBankLimitConfigs);
			String bankCode = StringUtils.isEmpty( p.getOutStlmId()) ? "ICBC" : p.getOutStlmId();
			if(m.containsKey(bankCode)){
				// 不用重新put，因为是引用
				m.get(bankCode).put("totalAmt",((BigDecimal)m.get(bankCode).get("totalAmt")).add(p.getMerTxnAmt()));
				((List)m.get(bankCode).get("gopayOrderIds")).add(p.getGopayOrderId());
			}else{
				Map<String,Object> mm = new HashMap<String, Object>();
				mm.put("totalAmt", p.getMerTxnAmt());
				List<String> gopayOrderIds = new ArrayList<String>();
				gopayOrderIds.add(p.getGopayOrderId());
				mm.put("gopayOrderIds", gopayOrderIds);
				m.put(bankCode, mm);
			}
		}
		
		return m;
		
	}


	/**
     * 初始化数据
     * 
     * @param curDate
     */
    protected void init(Date curDate) {
        // 查询最近一个月的法定工作日
        legalWorkList = autoSettleHelper.queryLegalWorkDayOfRecentOneMonth(curDate);

        logger.error("--legalWorkList=" + legalWorkList.toString());

        // 当前时间
        today = DateUtils.format(curDate, "yyyyMMdd");

        // 计算T-15的日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(curDate);
        calendar.add(Calendar.DAY_OF_MONTH, -STATI_DAYS);
        startDay = DateUtils.format(calendar.getTime(), "yyyyMMdd");

        logger.error("--today=" + today + ",startDay=" + startDay);
    }

    /**
     * 执行零点判断
     */
    protected void doZeroJudge() {
        // 查询订单之零点判断
        List<CpsGenMainOrder> mainList = autoSettleService.queryOrderOfJudge(startDay, today);
        
        logger.error("doZeroJudge--queryOrder--mainList.size=" + mainList.size());

        // 筛选出结算日为今天的订单
        List<CpsGenMainOrder> orderList = new ArrayList<CpsGenMainOrder>();
        for (CpsGenMainOrder main : mainList) {
            try{
                logger.error("checkTodayIsSettleDay------GopayOrderId=" + main.getGopayOrderId());
                if (checkTodayIsSettleDay(main, main.getTransDtlSq(), today, main.getRemark1(), main.getRemark2(),main.getOrderType(),main.getChildTranType())) {
                    orderList.add(main);
                }
            } catch (Exception e) {
                // 吃掉所有异常
                logger.error("checkTodayIsSettleDay Error", e);
            }
        }

        logger.error("doZeroJudge--queryOrder--orderIdList.size=" + orderList.size());

        // 调用CPS
        Object paramVo;
        CPSResponse response;
        CpsGenMainOrder main;
        for (int i = 0; i < orderList.size(); i++) {
            main = orderList.get(i);

            // 封装cps请求参数vo
            paramVo = buildCallCpsParamVo(main, true);

            logger.error("doZeroJudge------GopayOrderId=" + main.getGopayOrderId());
            try {
                // 调用cps
                response = callCPSHelper.callByVOTicket(paramVo);
                if (!ProcCodeConstants.PROC_CODE_100S1000.equals(response.getRespCode())) {
                    logger.error("------调用cps返回异常  response=" + response.getRespCode());
                }
            } catch (Exception e) {
                // 吃掉所有异常
                logger.error("callByVOTicket Error", e);
            }
        }

    }

    /**
     * 校验今天是否为结算日
     * 
     * @param main
     * @param settleCircle
     * @return
     */
    private boolean checkTodayIsSettleDay(CpsGenMainOrder main, int settleCircle, String today, String cardNum,
            String bankName,String bcFlag,String splitFlag) {
        //获取银行Code
//        String bankCode=autoSettleHelper.queryBankCodeByName(bankName);
//        String bankCode=autoSettleHelper.queryPayBankCode(main,bankName,bcFlag,cardNum);
        
//        String payCustId=IntTxnCd._01301.value.equals(main.getGopayIntTxnCd())?main.getMerId():main.getPayCustId();
    	String acctId=cloudCustAcctRelDao.getCloudAcct(main);//支持云账户的自动结算
        String bankCode = autoSettleBankCodeAdapter.queryHolidayPayBankCode(main, bankName, bcFlag, cardNum, null, acctId,splitFlag);
        logger.error("checkTodayIsSettleDay queryPayBankCode result bankCode="+bankCode);
        // 根据客户节假日白名单规则查询额外工作日
//        List<String> extraWorkList = autoSettleHelper.queryExtraWorkDayByCustHolidayRule(payCustId, cardNum,
//                bankCode, DateUtils.format(main.getGopayTxnTm(), "yyyyMMdd"), today,main.getGopayIntTxnCd());

        String ruleId = null;

        // 计算结算日
        String settleDay = null;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(main.getGopayTxnTm());
        int count = 0;
        for (int i = 1; i <= STATI_DAYS; i++) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            String tmpDay = DateUtils.format(calendar.getTime(), "yyyyMMdd");

            if (legalWorkList.contains(tmpDay)) {
                ruleId=null;
                count++;
            } else if(StringUtils.isNotBlank(bankCode)){
                ruleId = main.getGopayOrderId();
                count++;
            }

            if (count >= settleCircle) {
                settleDay = tmpDay;
                break;
            }
        }

        // 借用属性返回ruleId
        main.setRemark1(ruleId);

        return today.equals(settleDay);
    }

    /**
     * 封装cps请求参数vo
     * 
     * @param main 订单信息
     * @param isZeroJudge 是否为零点判断
     * @return
     */
    private Object buildCallCpsParamVo(CpsGenMainOrder main, boolean isZeroJudge) {
        String gopayOrderId = main.getGopayOrderId();
        String intTxnCd = main.getGopayIntTxnCd();
        String ruleId = main.getRemark1();

        Object obj = null;
        if (intTxnCd.equals(IntTxnCd._00700.value)) {
            Tran00700VO paramVo = new Tran00700VO();
            paramVo.setGopayOrderId(gopayOrderId);
            paramVo.setOpType(isZeroJudge ? PayBankOpType.AUTO_SETTLE_JOB_JUDGE : PayBankOpType.AUTO_SETTLE_JOB_BCDL);
            paramVo.setRuleId(isZeroJudge ? ruleId : null);

            obj = paramVo;
        } else if (intTxnCd.equals(IntTxnCd._00701.value)) {//退款转账 add by zhangyu
            Tran00701PortalVO paramVo = new Tran00701PortalVO();
            Tran00701VO tempVo = new Tran00701VO();
            tempVo.setGopayOrderId(gopayOrderId);
            tempVo.setOpType(isZeroJudge ? PayBankOpType.AUTO_SETTLE_JOB_JUDGE : PayBankOpType.AUTO_SETTLE_JOB_BCDL);
            tempVo.setRuleId(isZeroJudge ? ruleId : null);
            paramVo.setTran00701VO(tempVo);

            obj = paramVo;
        } else if (intTxnCd.equals(IntTxnCd._00800.value)) {
            Tran00800VO paramVo = new Tran00800VO();
            paramVo.setGopayOrderId(gopayOrderId);
            paramVo.setOpType(isZeroJudge ? DrawOpType.AUTO_SETTLE_JOB_JUDGE : DrawOpType.AUTO_SETTLE_JOB_BCDL);
            paramVo.setRuleId(isZeroJudge ? ruleId : null);

            obj = paramVo;
        } else if (intTxnCd.equals(IntTxnCd._01301.value)) {
            GP01301VO paramVo = new GP01301VO();
            paramVo.setGopayOrderId(gopayOrderId);
            paramVo.setStepType(isZeroJudge ? "7" : "8");// 7:自动结算之JOB零点判断
            paramVo.setRuleId(isZeroJudge ? ruleId : null);

            obj = paramVo;
        } else if (intTxnCd.equals(IntTxnCd._01605.value)){
        	Wallet01605VO paramVo = new Wallet01605VO();
        	paramVo.setGopayOrderId(gopayOrderId);
        	paramVo.setOpType(isZeroJudge ? Wallet01605OpType.AUTO_SETTLE_JOB_JUDGE : Wallet01605OpType.AUTO_SETTLE_JOB_BCDL);

            obj = paramVo;
        } else if (intTxnCd.equals(IntTxnCd._01606.value)){
        	Wallet01606VO paramVo = new Wallet01606VO();
        	paramVo.setGopayOrderId(gopayOrderId);
        	paramVo.setOpType(isZeroJudge ? Wallet01606OpType.AUTO_SETTLE_JOB_JUDGE : Wallet01606OpType.AUTO_SETTLE_JOB_BCDL);
        	
        	obj = paramVo;
        } else if (intTxnCd.equals(IntTxnCd._01617.value)){//天溢盈兑付到银行 add by zhoupeng 20170308
        	Wallet01617VO paramVo = new Wallet01617VO();
        	paramVo.setGopayOrderId(gopayOrderId);
        	paramVo.setOpType(isZeroJudge ? Wallet01617OpType.AUTO_SETTLE_JOB_JUDGE : Wallet01617OpType.AUTO_SETTLE_JOB_BCDL);
        	
        	obj = paramVo;
        }

        return obj;
    }
    
    private Object buildCallCpsParamVo4SettlementToday(CpsGenMainOrder main){
    	String gopayOrderId = main.getGopayOrderId();
        String intTxnCd = main.getGopayIntTxnCd();

        Object obj = null;
            Tran00700VO paramVo = new Tran00700VO();
            paramVo.setGopayOrderId(gopayOrderId);
            paramVo.setOpType(PayBankOpType.AUTO_SETTLE_SETTLEMENT_TODAY_LOCK_DEAL);

            obj = paramVo;

        return obj;
    }

    /**
     * 对结算日为节假日的T+N订单执行十点银企直连
     */
    protected void doTenBCDL() {
        // 查询订单之十点银企直连
        List<CpsGenMainOrder> orderList = autoSettleService.queryOrderOfBCDL(startDay, today);

        logger.error("doTenBCDL--queryOrder--orderList.size=" + orderList.size());


        // 调用CPS
        Object paramVo;
        CPSResponse response;
        CpsGenMainOrder main;
        for (int i = 0; i < orderList.size(); i++) {
            main = orderList.get(i);

            // 封装cps请求参数vo
            paramVo = buildCallCpsParamVo(main, false);

            logger.error("doTenBCDL------GopayOrderId=" + main.getGopayOrderId());
            try {
                // 调用cps
                response = callCPSHelper.callByVOTicket(paramVo);
                if (!ProcCodeConstants.PROC_CODE_100S1000.equals(response.getRespCode())) {
                    logger.error("------调用cps返回异常  response=" + response.getRespCode());
                }
            } catch (Exception e) {
                // 吃掉所有异常
                logger.error("callByVOTicket Error", e);
            }
        }
    }
    

    //TODO 潜在问题，如果以后新增自动结算银行，这里没有加相应的控制代码，则会导致按工行进行汇总，却按实际新增银行结算，可能产生备付金不够用的问题。
    private String getBankCode(String bankName, List<AsBankLimitConfig> asBankLimitConfigs){
    	if(bankName.indexOf("工行")!=-1 || bankName.indexOf("工商")!=-1){
    		return SettlementExchangeConstants.STLM_EX_ICBC;
    	}
    	if(bankName.indexOf("招行")!=-1 || bankName.indexOf("招商")!=-1){
    		return "CMB";
    	}
    	if(bankName.indexOf("农行")!=-1 || bankName.indexOf("农业银行")!=-1){
    		return SettlementExchangeConstants.STLM_EX_ABC;
    	}
    	
    	if(bankName.indexOf("中行")!=-1 || bankName.indexOf("中国银行")!=-1){
    		for (AsBankLimitConfig a : asBankLimitConfigs) {
				if("BOC".equals(a.getBankCode())){
					return "BOC";
				}
			}
    		return SettlementExchangeConstants.STLM_EX_ICBC;
    	}
    	
    	if(bankName.indexOf("建行")!=-1 || bankName.indexOf("建设银行")!=-1){
    		for (AsBankLimitConfig a : asBankLimitConfigs) {
				if("CCB".equals(a.getBankCode())){
					return "CCB";
				}
			}
    		return SettlementExchangeConstants.STLM_EX_ICBC;
    	}
    	
    	return SettlementExchangeConstants.STLM_EX_ICBC;
    }
    
    private String getAcctNo(String bankCode){
		if ("CMB".equals(bankCode)) {
			return "0203";
		} else if ("ABC".equals(bankCode)) {
			return "6292";
		} else if ("ICBC".equals(bankCode)) {
			return "7204";
		} else if ("BOC".equals(bankCode)) {
			return "0843";
		}
    	return bankCode;
    }
    
    
    private String getBankName(String bankCode){
		if ("ICBC".equals(bankCode)) {
			return "工商";
		} else if ("CMB".equals(bankCode)) {
			return "招商";

		} else if ("ABC".equals(bankCode)) {
			return "农业";
		} else if ("BOC".equals(bankCode)) {
			return "中国";
		} else if ("CCB".equals(bankCode)) {
			return "建设";
		} else {
			return bankCode;
		}
    }
}
